package com.example.star.view.activity;

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;

import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.example.star.R;
import com.example.star.adapter.ProductAdapter;
import com.example.star.api_service.ApiAddress;
import com.example.star.api_service.ApiBuyNow;
import com.example.star.api_service.ApiUser;
import com.example.star.entity.Address;
import com.example.star.entity.BuyNow;
import com.example.star.entity.User;
import com.example.star.retrofit.ApiClient;
import com.example.star.view.center.RechargeActivity;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class SettlementActivity extends AppCompatActivity implements ProductAdapter.OnQuantityChangeListener {

    private ListView productListView;
    private EditText shoppingAddressEditText;
    private Button submitButton;
    private Spinner addressSpinner;
    private ProductAdapter adapter;
    private ArrayList<String> starName;
    private ArrayList<String> perimeterTitles;
    private ArrayList<String> prices;
    private ArrayList<String> imageResources;
    private ArrayList<String> productTypes;
    private ArrayList<String> freights;
    private ArrayList<String> deliveryAddresses;
    private ArrayList<String> quantity;
    private ArrayList<String> totalPrice;
    private String loginPassword;
    private String userName;
    private List<Address> addressList = new ArrayList<>();
    private ArrayAdapter<String> addressAdapter;
    private TextView totalAmountTextView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_settlement);

        // 初始化视图组件
        productListView = findViewById(R.id.product_list_view);
        shoppingAddressEditText = findViewById(R.id.shopping_address_edit_text);
        submitButton = findViewById(R.id.submit_button);
        addressSpinner = findViewById(R.id.address_spinner);
        totalAmountTextView = findViewById(R.id.total_amount_text_view);

        // 获取传递过来的数据
        Intent intent = getIntent();
        starName = intent.getStringArrayListExtra("starName");
        perimeterTitles = intent.getStringArrayListExtra("perimeterTitles");
        prices = intent.getStringArrayListExtra("prices");
        imageResources = intent.getStringArrayListExtra("imageResources");
        productTypes = intent.getStringArrayListExtra("productTypes");
        freights = intent.getStringArrayListExtra("freights");
        deliveryAddresses = intent.getStringArrayListExtra("deliveryAddresses");
        quantity = intent.getStringArrayListExtra("quantity");
        totalPrice = intent.getStringArrayListExtra("totalPrice");
        userName = intent.getStringExtra("userName");

        // 从 SharedPreferences 中读取登陆密码和用户名
        SharedPreferences sharedPreferences = getSharedPreferences("user_info", MODE_PRIVATE);
        loginPassword = sharedPreferences.getString("loginPassword", "");
        userName = sharedPreferences.getString("username", "");

        // 设置ListView的适配器
        adapter = new ProductAdapter(imageResources, starName, perimeterTitles, prices, quantity);
        adapter.setOnQuantityChangeListener(this);
        productListView.setAdapter(adapter);

        // 从服务器获取该用户名对应的收货地址列表
        loadAddresses(userName);

        // 更新总金额显示
        updateTotalAmount();

        // 提交按钮点击事件
        submitButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String address;
                if (addressSpinner.getSelectedItemPosition() == 0) {
                    address = shoppingAddressEditText.getText().toString().trim();
                    if (address.isEmpty()) {
                        Toast.makeText(SettlementActivity.this, "请填写收货地址", Toast.LENGTH_SHORT).show();
                        return;
                    }
                } else {
                    address = addressAdapter.getItem(addressSpinner.getSelectedItemPosition());
                }

                showPasswordDialog(address);
            }
        });
    }

    private void loadAddresses(String userName) {
        ApiAddress apiAddress = ApiClient.getApiAddress();
        Call<List<Address>> call = apiAddress.getAddressByUserName(userName);
        call.enqueue(new Callback<List<Address>>() {
            @Override
            public void onResponse(Call<List<Address>> call, Response<List<Address>> response) {
                if (response.isSuccessful()) {
                    addressList = response.body();
                    List<String> addressDisplayList = new ArrayList<>();
                    addressDisplayList.add("填写新地址");
                    for (Address addr : addressList) {
                        addressDisplayList.add(addr.getAddress());
                    }

                    addressAdapter = new ArrayAdapter<>(SettlementActivity.this,
                            android.R.layout.simple_spinner_item, addressDisplayList);
                    addressAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
                    addressSpinner.setAdapter(addressAdapter);

                    addressSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
                        @Override
                        public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                            if (position == 0) {
                                shoppingAddressEditText.setVisibility(View.VISIBLE);
                            } else {
                                shoppingAddressEditText.setVisibility(View.GONE);
                            }
                        }

                        @Override
                        public void onNothingSelected(AdapterView<?> parent) {
                        }
                    });
                } else {
                    try {
                        String errorMessage = response.errorBody().string();
                        Toast.makeText(SettlementActivity.this, "获取地址失败: " + errorMessage, Toast.LENGTH_SHORT).show();
                    } catch (Exception e) {
                        Toast.makeText(SettlementActivity.this, "获取地址失败: 未知错误", Toast.LENGTH_SHORT).show();
                    }
                }
            }

            @Override
            public void onFailure(Call<List<Address>> call, Throwable t) {
                Toast.makeText(SettlementActivity.this, "网络请求失败: " + t.getMessage(), Toast.LENGTH_SHORT).show();
            }
        });
    }

    private void showPasswordDialog(final String address) {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        BigDecimal totalAmount = calculateTotalAmount();
        builder.setTitle("请输入支付密码");
        builder.setMessage("支付金额: " + totalAmount + "元");
        final EditText passwordEditText = new EditText(this);
        builder.setView(passwordEditText);
        builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                String password = passwordEditText.getText().toString().trim();
                if (password.equals(loginPassword)) {
                    BigDecimal totalAmount = calculateTotalAmount();
                    checkBalanceAndPay(userName, totalAmount, address);
                } else {
                    Toast.makeText(SettlementActivity.this, "密码错误", Toast.LENGTH_SHORT).show();
                }
            }
        });
        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                for (int i = 0; i < starName.size(); i++) {
                    BuyNow item = new BuyNow();
                    item.setUserName(userName);
                    item.setImageResource(imageResources.get(i));
                    item.setStarName(starName.get(i));
                    item.setTitle(perimeterTitles.get(i));
                    item.setProductType(productTypes.get(i));
                    item.setPrices(prices.get(i));
                    item.setFreight(freights.get(i));
                    item.setDeliveryAddress(deliveryAddresses.get(i));
                    item.setShoppingAddress(address);
                    item.setQuantity(quantity.get(i));
                    item.setTotalPrice(totalPrice.get(i));
                    item.setOrderStatus("待付款");

                    addToShoppingCart(item);
                }
                dialog.cancel();
            }
        });
        builder.show();
    }

    private BigDecimal calculateTotalAmount() {
        BigDecimal total = BigDecimal.ZERO;
        for (int i = 0; i < prices.size(); i++) {
            try {
                BigDecimal price = new BigDecimal(prices.get(i));
                int quantityValue = Integer.parseInt(adapter.getQuantity(i));
                total = total.add(price.multiply(new BigDecimal(quantityValue)));
            } catch (NumberFormatException e) {
                Toast.makeText(this, "价格或数量格式错误，请检查", Toast.LENGTH_SHORT).show();
                return BigDecimal.ZERO;
            }
        }
        return total;
    }

    private void updateTotalAmount() {
        BigDecimal totalAmount = calculateTotalAmount();
        totalAmountTextView.setText("¥"+ totalAmount);
    }

    private void checkBalanceAndPay(final String username, final BigDecimal totalAmount, final String address) {
        ApiUser apiUser = ApiClient.getApiUser();
        Call<BigDecimal> call = apiUser.checkMoney(username);
        call.enqueue(new Callback<BigDecimal>() {
            @Override
            public void onResponse(Call<BigDecimal> call, Response<BigDecimal> response) {
                if (response.isSuccessful()) {
                    BigDecimal balance = response.body();
                    if (balance != null && balance.compareTo(totalAmount) >= 0) {
                        performPayment(username, totalAmount, address);
                    } else {
                        Toast.makeText(SettlementActivity.this, "余额不足，请先充值", Toast.LENGTH_SHORT).show();
                        Intent intent = new Intent(SettlementActivity.this, RechargeActivity.class);
                        startActivity(intent);
                    }
                } else {
                    try {
                        String errorMessage = response.errorBody().string();
                        Toast.makeText(SettlementActivity.this, "检查余额失败: " + errorMessage, Toast.LENGTH_SHORT).show();
                    } catch (Exception e) {
                        Toast.makeText(SettlementActivity.this, "检查余额失败: 未知错误", Toast.LENGTH_SHORT).show();
                    }
                }
            }

            @Override
            public void onFailure(Call<BigDecimal> call, Throwable t) {
                Toast.makeText(SettlementActivity.this, "网络请求失败: " + t.getMessage(), Toast.LENGTH_SHORT).show();
            }
        });
    }

    private void performPayment(final String username, final BigDecimal totalAmount, final String address) {
        ApiUser apiUser = ApiClient.getApiUser();
        Call<User> call = apiUser.pay(username, totalAmount);
        call.enqueue(new Callback<User>() {
            @Override
            public void onResponse(Call<User> call, Response<User> response) {
                if (response.isSuccessful()) {
                    Toast.makeText(SettlementActivity.this, "支付成功，支付金额: " + totalAmount, Toast.LENGTH_SHORT).show();
                    for (int i = 0; i < starName.size(); i++) {
                        BuyNow item = new BuyNow();
                        item.setUserName(username);
                        item.setImageResource(imageResources.get(i));
                        item.setStarName(starName.get(i));
                        item.setTitle(perimeterTitles.get(i));
                        item.setProductType(productTypes.get(i));
                        item.setPrices(prices.get(i));
                        item.setFreight(freights.get(i));
                        item.setDeliveryAddress(deliveryAddresses.get(i));
                        item.setShoppingAddress(address);
                        item.setQuantity(adapter.getQuantity(i));
                        item.setTotalPrice(String.valueOf(new BigDecimal(prices.get(i)).multiply(new BigDecimal(adapter.getQuantity(i)))));
                        item.setOrderStatus("待收货");

                        addToShoppingCart(item);
                    }
                    finish();
                } else {
                    try {
                        String errorMessage = response.errorBody().string();
                        Toast.makeText(SettlementActivity.this, "支付失败: " + errorMessage, Toast.LENGTH_SHORT).show();
                    } catch (Exception e) {
                        Toast.makeText(SettlementActivity.this, "支付失败: 未知错误", Toast.LENGTH_SHORT).show();
                    }
                }
            }

            @Override
            public void onFailure(Call<User> call, Throwable t) {
                Toast.makeText(SettlementActivity.this, "网络请求失败: " + t.getMessage(), Toast.LENGTH_SHORT).show();
            }
        });
    }

    private void addToShoppingCart(BuyNow buyNow) {
        ApiBuyNow apiBuyNow = ApiClient.getApiBuyNow();
        Call<BuyNow> call = apiBuyNow.saveBuyNow(buyNow);
        call.enqueue(new Callback<BuyNow>() {
            @Override
            public void onResponse(Call<BuyNow> call, Response<BuyNow> response) {
                if (response.isSuccessful()) {
                    Toast.makeText(SettlementActivity.this, "订单已保存，状态：" + buyNow.getOrderStatus(), Toast.LENGTH_SHORT).show();
                } else {
                    try {
                        String errorMessage = response.errorBody().string();
                        Toast.makeText(SettlementActivity.this, "保存订单失败: " + errorMessage, Toast.LENGTH_SHORT).show();
                    } catch (Exception e) {
                        Toast.makeText(SettlementActivity.this, "保存订单失败: 未知错误", Toast.LENGTH_SHORT).show();
                    }
                }
            }

            @Override
            public void onFailure(Call<BuyNow> call, Throwable t) {
                Toast.makeText(SettlementActivity.this, "网络请求失败: " + t.getMessage(), Toast.LENGTH_SHORT).show();
            }
        });
    }

    @Override
    public void onQuantityChanged() {
        updateTotalAmount();
    }
}